package com.zhgxi.zf.service;

import java.util.List;

import javax.annotation.Resource;

import org.slave4j.orm.Filtration;
import org.slave4j.orm.Filtration.MatchType;
import org.slave4j.orm.hibernate.BaseDao;
import org.slave4j.orm.hibernate.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhgxi.zf.entity.User;

@Service
@Transactional
public class UserService extends BaseService<User> {

	@Override
	@Resource(name = "userDao")
	public void setBaseDao(BaseDao<User> baseDao) {
		this.baseDao = baseDao;
	}

	public User login(User user) {
		Filtration username = new Filtration(MatchType.EQ, user.getUsername(), "username");
		Filtration password = new Filtration(MatchType.EQ, user.getPassword(), "password");
		Filtration visible = new Filtration(MatchType.EQ, true, "visible");
		for (User u : baseDao.findList(username, password, visible)) {
			return u;
		}
		return null;
	}

	public boolean saveUser(User user) {
		try {
			if (user.isNew() || user.getId() == 0) {
				baseDao.save(user);
			} else {
				baseDao.update(user);
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<User> findAllUser() {
		Filtration visible = new Filtration(MatchType.EQ, true, "visible");
		List<User> list = baseDao.findList(visible);
		return list;
	}

	public boolean deleteUser(Integer uid) {
		try {
			baseDao.unVisible(uid);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<User> findByUname(String uname) {
		Filtration likeUname = new Filtration(MatchType.LIKE, uname, "username");
		Filtration visible = new Filtration(MatchType.EQ, true, "visible");
		return baseDao.findList(likeUname, visible);
	}
	

}
